<template>
  <div class="wrap-container">
    <div class="search_box">
      <div class="search_tit">
        <div class="manage_tit">
          <div class="line"></div>
          <span class="ml-2">优惠券筛选</span>
        </div>
      </div>
      <el-form :inline="true" label-position="left" label-width="76px">
        <el-form-item label="优惠券名称">
          <el-input
            clearable
            v-model="queryParams.name"
            placeholder="请输入名字/场馆备注/渠道备注"
          ></el-input>
        </el-form-item>
        <el-form-item label="优惠券编码">
          <el-input clearable v-model="queryParams.code" placeholder="请输入券码"></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select filterable v-model="queryParams.type" placeholder="请选择" clearable>
            <el-option
              :label="dict.label"
              :value="dict.value"
              v-for="dict in dict?.type?.coupon_type"
              :key="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布渠道">
          <el-select filterable v-model="queryParams.sourceType" placeholder="请选择" clearable>
            <el-option
              :label="dict.label"
              :value="dict.value"
              v-for="dict in dict?.type?.platform_type"
              :key="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="queryParams.lifespanStartTime"
            type="date"
            placeholder="请选择"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_box">
      <div class="tabs_box">
        <el-tabs v-model="tabsVal" @tab-change="handleClick">
          <el-tab-pane
            :label="`${item.label}`"
            :name="item.value"
            v-for="item in tabsList"
            :key="item.value"
          >
            <template #label> {{ item.label }} ({{ item.count }}) </template>
          </el-tab-pane>
        </el-tabs>
        <!-- <div class="handle_btn">
          <el-button class="del_btn" @click="handleDel(1)">批量删除</el-button>
        </div> -->
      </div>
      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column label="优惠券编码" prop="code" width="100" />
        <el-table-column label="优惠券名称" prop="name" show-overflow-tooltip />
        <el-table-column label="优惠券类型" prop="type" width="100">
          <template #default="{ row }">
            {{ handleCouponsType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="使用条件" width="150">
          <template #default="{ row }">
            <div v-if="row.type == 3">满{{ row.thresholdAmount }}减{{ row.faceValue }}</div>
            <div v-else-if="row.type == 2">抵扣{{ row.freeHours }}小时</div>
            <!-- <div
              v-else-if="
                row.type == 2 && row.discountType == 4 && row.cardType == 1
              "
            >
              次卡
            </div>
            <div
              v-else-if="
                row.type == 2 && row.discountType == 4 && row.cardType == 2
              "
            >
              周卡
            </div>
            <div
              v-else-if="
                row.type == 2 && row.discountType == 4 && row.cardType == 3
              "
            >
              月卡
            </div> -->
            <div v-else>无门槛</div>
          </template>
        </el-table-column>
        <el-table-column
          label="渠道备注"
          prop="mname"
          :formatter="formatter"
          show-overflow-tooltip
        />
        <el-table-column
          label="场馆备注"
          prop="bname"
          :formatter="formatter"
          show-overflow-tooltip
        />
        <el-table-column label="发布渠道" prop="sourceType" width="100">
          <template #default="{ row }">
            {{ handleSourceType(row.sourceType) }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" prop="audit" width="120">
          <template #default="{ row }">
            <div class="flex items-center" v-if="row.audit == 0">
              <i class="block w-3px h-3px bg-color-0988FB rounded-full mr-5px"></i>
              <span style="color: #0988fb">待审核</span>
            </div>
            <div class="flex items-center" v-else-if="row.audit == 1">
              <i class="block w-3px h-3px bg-color-43CF7C rounded-full mr-5px"></i>
              <span style="color: #43cf7c">审核通过</span>
            </div>
            <div class="flex items-center" v-else-if="row.audit == 2">
              <i class="block w-3px h-3px bg-color-D43030 rounded-full mr-5px"></i>
              <span style="color: #d43030">驳回</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="审核人" prop="auditUser" :formatter="formatter" width="100" />
        <el-table-column label="创建日期" prop="createTime" width="150" />
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <div class="table_btn">
              <el-button
                class="primary_text"
                type="text"
                @click="handleUpdate(row.id)"
                v-show="row.audit == 2"
                v-hasPermi="['sys:approval:btn_coupon_edit']"
                >去修改</el-button
              >
              <el-button
                class="primary_text"
                type="text"
                @click="handleDetail(row)"
                v-show="row.audit != 2"
                v-hasPermi="['sys:approval:btn_coupon_view']"
                style="margin-left: 0"
                >详情</el-button
              >
              <!-- <el-button
                type="text"
                @click="handleDel(0, row.id)"
                v-hasPermi="['sys:approval:btn_del']"
                >删除</el-button
              > -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { couponAuditList, countCouponAuditList } from '@/api/coupon/approval'
import { useDict } from '@/utils/dict'

// 定义类型
interface QueryParams {
  pageNum: number
  pageSize: number
  code: string | null
  name: string | null
  type: string | null
  sourceType: string | null
  lifespanStartTime: string | null
}

interface TabItem {
  label: string
  value: string
  count: number
}

interface TableDataItem {
  id: number
  code: string
  name: string
  type: string
  thresholdAmount: string
  faceValue: string
  freeHours: string
  mname: string
  bname: string
  sourceType: string
  audit: number
  auditUser: string
  createTime: string
}

// 使用 vue-router
const router = useRouter()

// 字典数据（从全局 mixin 注入）
const { dict }: any = useDict({
  type: 'coupon_type',
})

// 响应式数据
const loading = ref(false)
const total = ref(0)
const tabsVal = ref('-1')
const tableData = ref<TableDataItem[]>([])
const multipleSelection = ref<TableDataItem[]>([])

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  code: null,
  name: null,
  type: null,
  sourceType: null,
  lifespanStartTime: null,
})

const tabsList = ref<TabItem[]>([
  { label: '全部', value: '-1', count: 0 },
  { label: '待审核', value: '0', count: 0 },
  { label: '审核完成', value: '1', count: 0 },
  { label: '驳回', value: '2', count: 0 },
])

// 方法定义
// 优惠券审核列表
const getList = async () => {
  loading.value = true
  try {
    const res: any = await couponAuditList({
      ...queryParams,
      audit: tabsVal.value == '-1' ? '' : tabsVal.value,
    })
    tableData.value = res.rows
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 优惠券审核列表统计
const getCount = async () => {
  const { data }: any = await countCouponAuditList(queryParams)
  if (data) {
    if (tabsList.value[0]) tabsList.value[0].count = data.countAll || 0
    if (tabsList.value[1]) tabsList.value[1].count = data.dspCount || 0
    if (tabsList.value[2]) tabsList.value[2].count = data.auditCount || 0
    if (tabsList.value[3]) tabsList.value[3].count = data.unAuditCount || 0
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
  getCount()
}

// 重置
const reset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
    type: null,
    sourceType: null,
    lifespanStartTime: null,
    audit: null,
  })
  getList()
  getCount()
}

// 选项卡切换
const handleClick = () => {
  queryParams.pageNum = 1
  getList()
}

// 优惠券类型
const handleCouponsType = (val: string) => {
  const item = dict?.type?.coupon_type?.find((item: any) => item.value == val)
  return item ? item.label : '--'
}

// 优惠券发布渠道
const handleSourceType = (val: string) => {
  const item = dict?.type?.platform_type.find((item: any) => item.value == val)
  return item ? item.label : '--'
}

// 表格多选
const handleSelectionChange = (val: TableDataItem[]) => {
  multipleSelection.value = val
}

// 查看详情
const handleDetail = (item: TableDataItem) => {
  router.push({
    path: '/approval/couApprovalDetail',
    query: { id: String(item.id), audit: String(item.audit), type: '0' },
  })
}

// 去修改
const handleUpdate = (id: number) => {
  router.push({
    path: '/coupon/updateV3',
    query: { data: String(id), type: '0', from: 'approval' },
  })
}

// 格式化单元格
const formatter = (row: any, column: any, cellValue: any) => {
  // 如果单元格值为空或为 null，返回 '--'
  return cellValue || '--'
}

// 生命周期
onMounted(() => {
  getList()
  getCount()
})
</script>

<style lang="scss" scoped>
.search_box {
  padding-bottom: 0;
}
.table_box {
  position: relative;
  padding-top: 6px;
  .tabs_box {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-bottom: 15px;
    :deep(.el-tabs) {
      flex: 1;
      .el-tabs__header {
        margin: 0;
      }
    }
  }
  .handle_btn {
    margin-left: 35px;
    .el-button {
      padding: 0;
      width: 90px;
      height: 35px;
      line-height: 35px;
    }
  }
}
:deep(.el-table .el-table__body td .cell .line-limit-length:empty::after) {
  content: '--';
}
</style>
